package top.v5it.japi.plus.data.support.repository.impl;

import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import top.v5it.japi.plus.data.support.entity.*;
import top.v5it.japi.plus.data.support.repository.EntityDataRepository;

import java.util.List;

/**
 * JDBC实现获取框架支持必要实体数据服务
 *
 * @author zhanpu
 * @date 2022/6/13
 */
@AllArgsConstructor
public class JdbcEntityDataRepository implements EntityDataRepository {

    private final JdbcTemplate jdbcTemplate;

    /**
     * 根据实体类型获取{@link RowMapper}
     *
     * @param clazz 实体class
     * @param <T>   实体类型
     * @return {@link BeanPropertyRowMapper}
     */
    private <T> RowMapper<T> mapper(Class<T> clazz) {
        BeanPropertyRowMapper<T> rowMapper = new BeanPropertyRowMapper<>();
        rowMapper.setMappedClass(clazz);
        return rowMapper;
    }

    @Override
    public List<Cert> certs() {
        return jdbcTemplate.query(EntityDataRepository.SELECT_CERTS, mapper(Cert.class));
    }

    @Override
    public List<Channel> channels() {
        return jdbcTemplate.query(EntityDataRepository.SELECT_CHANNELS, mapper(Channel.class));
    }

    @Override
    public List<ClientCert> clientCerts() {
        return jdbcTemplate.query(EntityDataRepository.SELECT_CLIENTCERTS, mapper(ClientCert.class));
    }

    @Override
    public List<SiteChannel> siteChannels() {
        return jdbcTemplate.query(EntityDataRepository.SELECT_SITECHANNELS, mapper(SiteChannel.class));
    }

    @Override
    public List<KeyChannel> keyChannels() {
        return jdbcTemplate.query(EntityDataRepository.SELECT_KEYCHANNELS, mapper(KeyChannel.class));
    }

}
